package filter;

import javax.servlet.*;
import java.io.IOException;
import java.util.Enumeration;

/**
 * 演示FilterConfig使用
 *
 */
public class LmyFilterConfig implements Filter {

    private String ip;  //从配置获取ip

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("LmyFilterConfig init被调用...");
        //通过filterConfig 获取 相关的参数
        //web.xml配置的 <filter-name>
        System.out.println("filterName = " + filterConfig.getFilterName());

        //获取<init-param>属性
        ip = filterConfig.getInitParameter("ip");
        System.out.println("ip = " + filterConfig.getInitParameter("ip"));

        //获取全局对象servletContext，用于和其他servlet通讯
        ServletContext servletContext = filterConfig.getServletContext();
        System.out.println("servletContext = " + servletContext);

        //可以获取到该filter所有的配置参数名
        Enumeration<String> initParameterNames = filterConfig.getInitParameterNames();
        //遍历枚举
        while (initParameterNames.hasMoreElements()) {
            System.out.println("名字= " + initParameterNames.nextElement());
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("LmyFilterConfig doFilter被调用...");
        //通过forbidden   ip来进行控制
        //获取到访问ip
        String remoteAddr = servletRequest.getRemoteAddr();
        System.out.println(remoteAddr);
        if (remoteAddr.contains(ip)) {
            System.out.println("封杀该网段...");
            //转发到登录页面
            servletRequest.getRequestDispatcher("/login.jsp")
                    .forward(servletRequest, servletResponse);
            return; //直接返回
        }

        //继续访问目标资源
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
